<template>
  <div
    class="image-widget"
    :style="{
      width: Number(props.width) + 'px',
      height: Number(props.height) + 'px',
      background: props.bgColor || 'none',
      overflow: 'hidden',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    }"
  >
    <img
      :src="currentUrl || notFoundImg"
      :key="imgKey"
      @error="onImgError"
      alt=""
      :style="getImgStyle()"
    />
  </div>
</template>

<script setup lang="ts">
import { withDefaults, defineProps, ref, watch, nextTick } from 'vue'
import { ComponentInstance } from '@/types/visual-app';
import notFoundImg from '@/assets/img/state/404.png'

const props = defineProps<ComponentInstance>()
const currentUrl = ref(notFoundImg)
const currentStyle = ref({}) // 初始化为空对象
const imgKey = ref(Date.now())

import { axiosInstance } from '@/utils/http/index'
const BASE_API = axiosInstance.defaults.baseURL

// 监听 props 变更
watch(
  () => props.config?.attributes?.props,
  (val) => {
    if (val?.src) {
      if (!val.src) {
        currentUrl.value = notFoundImg;
      } else if (/^(https?:)?\/\//i.test(val.src)) {
        currentUrl.value = val.src;
      } else {
        currentUrl.value = BASE_API + '/visual/material/image/' + val.src + '?' + new Date().getTime();
      }
    }

    if (val?.css) {
      currentStyle.value = val.css; // 直接赋值
    }
  },
  { immediate: true, deep: true }
)

const getImgStyle = () => {
  // 确保 currentStyle.value 是普通对象
  const style = "width: 100%; height: 100%;display:block;"+currentStyle.value
  return style;
};

function onImgError(e: Event) {
  currentUrl.value = notFoundImg
}
</script>

<style scoped>
.image-widget {
  box-sizing: border-box;
  border: 0px solid #e0e0e0;
  background: none;
  transition: box-shadow 0.2s;
}
</style> 